package tech.yixiyun.framework.kuafu.controller.request.param;

import com.fasterxml.jackson.databind.JsonNode;
import tech.yixiyun.framework.kuafu.bean.annotation.Priority;
import tech.yixiyun.framework.kuafu.controller.annotation.ContentType;
import tech.yixiyun.framework.kuafu.controller.cookie.CookieKit;
import tech.yixiyun.framework.kuafu.controller.request.KuafuRequest;
import tech.yixiyun.framework.kuafu.controller.session.SessionKit;
import tech.yixiyun.framework.kuafu.kits.StringKit;

import java.util.Map;

@Priority(0)
@ContentType({"application/json"})
public class JSONRequestParamResolver implements IRequestParamResolver {



    @Override
    public Object resolve(KuafuRequest request, ParamDefinition param) {
        if (param.getUrlParamIndex() > -1) { //这个参数是一个url参数
            Map<Integer, String> map = request.getUrlParameterMap();
            if (map.containsKey(param.getUrlParamIndex())) {
                return StringKit.convert(map.get(param.getUrlParamIndex()), param.getParameter().getType());
            }
        }

        //这个参数来自session绑定
        if (StringKit.isNotBlank(param.getSessionAttrName())) {
            return SessionKit.getAttribute(param.getSessionAttrName());
        }

        //如果这个参数来自cookie绑定
        if (StringKit.isNotBlank(param.getCookieAttrName())) {
            String cookie = CookieKit.getCookie(param.getCookieAttrName());
            return parseJSONToObject(cookie, param);
        }

        //如果这个参数来自request绑定的
        Object attribute = request.getAttribute(param.getName());
        if (attribute != null) {
            return attribute;
        }

        //是个普通参数
        Map<String, JsonNode> jsonMap = request.getJSONParameterMap();
        JsonNode value = null;
        //先看json中有没有它，必须用containsKey判断
        //不能通过get值是否==null判断，因为map中没这个key，get也会返回null
        if (jsonMap.containsKey(param.getName())) {
            value = jsonMap.get(param.getName());
            return parseJSONToObject(param.getParamFeature().getParamType() == ParamType.COMMON ? value.asText() : value.toString(),
                    param);
        } else {
            return ParamUtil.compose(param, request.getCommonParameterMap().get(param.getName()));
        }
    }
}
